package com.xjrsoft.module.customer.erp_model.eRP_SalesOutBand.service.impl;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.dbmodel.utils.DataSourceUtil;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.customer.erp_model.eRP_SalesOutBand.dto.ErpSalesoutbandDto;
import com.xjrsoft.module.customer.erp_model.eRP_SalesOutBand.dto.ErpSalesoutbandenrtyDto;
import com.xjrsoft.module.customer.erp_model.eRP_SalesOutBand.entity.ErpSalesoutband;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xjrsoft.module.customer.erp_model.eRP_SalesOutBand.entity.ErpSalesoutbandenrty;
import com.xjrsoft.module.customer.erp_model.eRP_SalesOutBand.mapper.ErpSalesoutbandenrtyMapper;
import com.xjrsoft.module.customer.erp_model.eRP_SalesOutBand.dto.ErpSalesoutbandListDto;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.xjrsoft.module.customer.erp_model.eRP_SalesOutBand.mapper.ErpSalesoutbandMapper;
import com.xjrsoft.module.customer.erp_model.eRP_SalesOutBand.service.IErpSalesoutbandService;
import com.xjrsoft.core.mp.base.BaseService;
import com.xjrsoft.module.customer.erp_model.eRP_SalesOutBand.vo.ErpSalesoutbandenrtyVo;
import com.xjrsoft.module.customer.erp_model.erp_inventoryManage.entity.ErpInventory;
import com.xjrsoft.module.customer.erp_model.erp_inventoryManage.service.IErpInventoryService;
import com.xjrsoft.module.customer.erp_model.salesOrder.entity.ErpSalesorder;
import com.xjrsoft.module.customer.erp_model.salesOrder.entity.ErpSalesorderentry;
import com.xjrsoft.module.customer.erp_model.salesOrder.service.IErpSalesorderService;
import com.xjrsoft.module.customer.erp_model.salesOrder.service.IErpSalesorderentryService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

/**
 *  服务实现类
 *
 * @author pp
 * @since 2021-10-08
 */
@Service
@AllArgsConstructor
public class ErpSalesoutbandServiceImpl extends BaseService<ErpSalesoutbandMapper, ErpSalesoutband> implements IErpSalesoutbandService {

	@Autowired
	private IErpInventoryService erpInventoryService;
	@Autowired
	private IErpSalesorderentryService erpSalesorderentryService;

	@Autowired
	private IErpSalesorderService erpSalesorderService;
	@Autowired
	private ErpSalesoutbandenrtyMapper erpSalesoutbandenrtyMapper;

	@Override
	public IPage<ErpSalesoutband> getPageList(ErpSalesoutbandListDto pageListDto) {
		Wrapper<ErpSalesoutband> wrapper = Wrappers.<ErpSalesoutband>query().lambda()				.eq(!StringUtil.isEmpty(pageListDto.getF_SalesOutCode()), ErpSalesoutband::getFSalesoutcode, pageListDto.getF_SalesOutCode())
				.eq(!StringUtil.isEmpty(pageListDto.getF_SalesOrderId()), ErpSalesoutband::getFSalesorderid, pageListDto.getF_SalesOrderId())
				.ge(!StringUtil.isEmpty(pageListDto.getF_SalesOutDate_Start()), ErpSalesoutband::getFSalesoutdate, pageListDto.getF_SalesOutDate_Start())
				.le(!StringUtil.isEmpty(pageListDto.getF_SalesOutDate_End()), ErpSalesoutband::getFSalesoutdate, pageListDto.getF_SalesOutDate_End())
				.eq(!StringUtil.isEmpty(pageListDto.getF_WarehouseId()), ErpSalesoutband::getFWarehouseid, pageListDto.getF_WarehouseId());
		return this.page(ConventPage.getPage(pageListDto), wrapper);
	}

	@SneakyThrows
	@Override
	public String addErpSalesoutband(ErpSalesoutband erpSalesoutband, ErpSalesoutbandDto erpSalesoutbandDto, List<ErpSalesoutbandenrtyDto> erpSalesoutbandenrtyListDto, List<ErpSalesoutbandenrty> erpSalesoutbandenrtyList) {
		if(updateInfo(erpSalesoutbandDto,erpSalesoutbandenrtyListDto,erpSalesoutbandenrtyList)==null){
            String erpSalesoutbandId = IdWorker.get32UUID();
            erpSalesoutband.setFId(erpSalesoutbandId);
            erpSalesoutbandenrtyList.forEach(erpSalesoutbandenrty -> erpSalesoutbandenrty.setFSalesoutid(erpSalesoutbandId));
            this.saveBatch(erpSalesoutbandenrtyList, ErpSalesoutbandenrty.class, ErpSalesoutbandenrtyMapper.class);
            boolean isSuccess = this.save(erpSalesoutband);
            return isSuccess ? erpSalesoutbandId : null;
        }else
        {
            return  "库存不足，请检查该仓库的商品库存";
        }
	}

	public  String updateInfo( ErpSalesoutbandDto erpSalesoutbandDto, List<ErpSalesoutbandenrtyDto> erpSalesoutbandenrtyListDto,List<ErpSalesoutbandenrty> erpSalesoutbandenrtyList) throws SQLException {
		boolean isNoQua=false;
		//判断库存是否足够
		for (int i=0;i<erpSalesoutbandenrtyListDto.size();i++)
		{
			String sql1="select * from erp_inventory i where i.F_WareHouseId='"+erpSalesoutbandDto.getFWarehouseid()+"'and i.F_GoodsId='"+erpSalesoutbandenrtyListDto.get(i).getFGoodsid()+"'";
			List<Entity> inventoryList= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
			if(inventoryList.size()>0) {
				if (erpSalesoutbandenrtyListDto.get(i).getFUnit().equals(erpSalesoutbandenrtyListDto.get(i).getFBasicunit())) {
					Integer amount = inventoryList.get(0).getInt("F_BasicAmount");
					if (erpSalesoutbandenrtyListDto.get(i).getFQuantity().compareTo(amount) == 1) {
						isNoQua = true;
					}
				} else if (erpSalesoutbandenrtyListDto.get(i).getFUnit().equals(erpSalesoutbandenrtyListDto.get(i).getFComunit())) {
					Integer amount = inventoryList.get(0).getInt("F_ComAmount");
					if (erpSalesoutbandenrtyListDto.get(i).getFQuantity().compareTo(amount) > 0) {
						isNoQua = true;
					}
				} else {
					BigDecimal converTate = null;
					//查询转换率
					BigDecimal baseConverRate = null;
					//显示单位转换率
					BigDecimal comConverRate=null;
					String sql2 = "select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='" + erpSalesoutbandenrtyListDto.get(i).getFUnitid() + "'";
					List<Entity> list = Db.use(DataSourceUtil.getDataSource("localDB")).query(sql2);
					for (int j = 0; j < list.size(); j++) {
						if (list.get(j).get("f_fullname").toString().equals(erpSalesoutbandenrtyListDto.get(i).getFComunit().toString()))
						{
							comConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
						if (list.get(j).get("f_fullname").toString().equals(erpSalesoutbandenrtyListDto.get(i).getFBasicunit().toString()))
						{
							baseConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
					}
					BigDecimal amount1 = inventoryList.get(0).getBigDecimal("F_BasicAmount");
					BigDecimal amount2 = inventoryList.get(0).getBigDecimal("F_ComAmount");
					if (new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFQuantity()).multiply(baseConverRate).compareTo(amount1) >0 || new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFQuantity()).multiply(comConverRate).compareTo(amount2) >0) {
						isNoQua = true;
					}
				}
			}
			else {
				isNoQua=true;
			}
		}
		if(isNoQua)
		{
			return "库存不足，请检查该仓库的商品库存";
		}
		List<ErpSalesorderentry> erpSalesorderentryList=new ArrayList<ErpSalesorderentry>();
		ErpSalesorder erpSalesorder=new ErpSalesorder();
		Integer status=erpSalesoutbandDto.getFStatus();
		List<Integer> statusList=new ArrayList<Integer>();
		for (int i=0;i<erpSalesoutbandenrtyListDto.size();i++)
		{
			ErpSalesorderentry erpSalesorderentry=new ErpSalesorderentry();
			//入库单位和基本单位和库存显示单位都一样可以直接做操作  1.对库存做操作（新增或修改）
			if(erpSalesoutbandenrtyListDto.get(i).getFBasicunit().equals(erpSalesoutbandenrtyListDto.get(i).getFUnit())&&erpSalesoutbandenrtyListDto.get(i).getFComunit().equals(erpSalesoutbandenrtyListDto.get(i).getFUnit()))
			{
				//根据商品id和仓库id查询是否有此商品的库存数据
				String sql1="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpSalesoutbandDto.getFWarehouseid()+ "' and i.F_GoodsId='"+erpSalesoutbandenrtyListDto.get(i).getFGoodsid()+"'";
				List<Entity> isInventory1= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
				ErpInventory erpInventory1=new ErpInventory();
				//如果有的话就修改对应商品的库存
				if (isInventory1.size()>0)
				{
					//修改数量=原有的数据-本次出库的数量
					BigDecimal aftBasicQua= isInventory1.get(0).getBigDecimal("f_basicamount");
					BigDecimal aftComamQua=isInventory1.get(0).getBigDecimal("f_comamount");
					BigDecimal receiptQua=new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFQuantity());
					erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
					erpInventory1.setFGoodsid(erpSalesoutbandenrtyListDto.get(i).getFGoodsid());
					erpInventory1.setFWarehouseid(erpSalesoutbandDto.getFWarehouseid());
					erpInventory1.setFBasicamount(aftBasicQua.subtract(receiptQua));
					erpInventory1.setFComamount(aftComamQua.subtract(receiptQua));
					//怎么在一个serveimp里去调用另外一个里面的方法 一定要注入
					erpInventoryService.updateById(erpInventory1);
					erpSalesorderentry.setFId(erpSalesoutbandenrtyListDto.get(i).getFOrderentryid());
					erpSalesorderentry.setFGoodsid(erpSalesoutbandenrtyListDto.get(i).getFGoodsid());
					//未出库数量=总数量-（已出库数量+本次出库数量）
					erpSalesorderentry.setFNooutqua(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFOrderqua()).subtract(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFOutqua()).add(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFQuantity()))).intValue());
					//已入库数量=总数量-未入库数量
					erpSalesorderentry.setFOutqua(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFOrderqua()).subtract(new BigDecimal(erpSalesorderentry.getFNooutqua())).intValue());
					erpSalesorderentryList.add(erpSalesorderentry);
					if(erpSalesorderentry.getFNooutqua()<0||erpSalesorderentry.getFNooutqua()==0)
					{
						statusList.add(status);
					}
				}
			}
			//不一样先查询换算率得到之后转换
			else {
				//这里组合有四种情况  只有同时满足不相等的情况 才需要同时转换
				//基本单位转换率
				BigDecimal baseConverRate = null;
				//显示单位转换率
				BigDecimal comConverRate=null;
				if(!erpSalesoutbandenrtyListDto.get(i).getFBasicunit().equals(erpSalesoutbandenrtyListDto.get(i).getFUnit()) &&!erpSalesoutbandenrtyListDto.get(i).getFComunit().equals(erpSalesoutbandenrtyListDto.get(i).getFUnit()))
				{
					//查询转换率
					String sql="select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='"+erpSalesoutbandenrtyListDto.get(i).getFUnit()+"'";
					List<Entity>  list= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql);
					for (int j=0;j<list.size();j++)
					{
						if (list.get(j).get("f_fullname").toString().equals(erpSalesoutbandenrtyListDto.get(i).getFComunit().toString()))
						{
							comConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
						if (list.get(j).get("f_fullname").toString().equals(erpSalesoutbandenrtyListDto.get(i).getFBasicunit().toString()))
						{
							baseConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
					}
					//得到转换率之后开始转换
					//根据商品id和仓库id查询是否有此商品的库存数据
					String sql1="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpSalesoutbandDto.getFWarehouseid()+ "' and i.F_GoodsId='"+erpSalesoutbandenrtyListDto.get(i).getFGoodsid()+"'";
					List<Entity> isInventory1=Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
					ErpInventory erpInventory1=new ErpInventory();
					BigDecimal receiptQua=new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFQuantity());
					//如果有的话就修改对应商品的库存
					if (isInventory1.size()>0)
					{
						//修改数量=原有的数据+本次入库的数量*转换率
						BigDecimal aftBasicQua= isInventory1.get(0).getBigDecimal("f_basicamount");
						BigDecimal aftComamQua=isInventory1.get(0).getBigDecimal("f_comamount");
						erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
						erpInventory1.setFWarehouseid(erpSalesoutbandDto.getFWarehouseid());
						erpInventory1.setFBasicamount(aftBasicQua.subtract(receiptQua.multiply(baseConverRate)));
						erpInventory1.setFComamount(aftComamQua.subtract(receiptQua.multiply(comConverRate)));
						erpInventoryService.updateById(erpInventory1);
						erpSalesorderentry.setFId(erpSalesoutbandenrtyListDto.get(i).getFOrderentryid());
						erpSalesorderentry.setFGoodsid(erpSalesoutbandenrtyListDto.get(i).getFGoodsid());
						//未出库数量=总数量-（已出库数量+本次出库数量）
						erpSalesorderentry.setFNooutqua(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFOrderqua()).subtract(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFOutqua()).add(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFQuantity()))).intValue());
						//已出库数量=总数量-未出库数量
						erpSalesorderentry.setFOutqua(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFOrderqua()).subtract(new BigDecimal(erpSalesorderentry.getFNooutqua())).intValue());
						erpSalesorderentryList.add(erpSalesorderentry);
						if(erpSalesorderentry.getFNooutqua()<0||erpSalesorderentry.getFNooutqua()==0)
						{
							statusList.add(status);
						}
					}
				}
				else {
					//其中一个需要转换 先判断是基本数量单位需要转换还是库存显示单位需要转换
					//如果库存显示单位和入库单位不相等 就需要转换,否则就是基本单位需要转换
					//先查询出转换率
					String sql="select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='"+erpSalesoutbandenrtyListDto.get(i).getFUnit()+"'";
					List<Entity>  list= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql);

					for (int j=0;j<list.size();j++)
					{
						if (list.get(j).get("f_fullname").toString().equals(erpSalesoutbandenrtyListDto.get(i).getFComunit().toString()))
						{
							comConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
						if (list.get(j).get("f_fullname").toString().equals(erpSalesoutbandenrtyListDto.get(i).getFBasicunit().toString()))
						{
							baseConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
						}
					}
					//得到转换率之后开始转换
					//根据商品id和仓库id查询是否有此商品的库存数据
					String sql1="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpSalesoutbandDto.getFWarehouseid()+ "' and i.F_GoodsId='"+erpSalesoutbandenrtyListDto.get(i).getFGoodsid()+"'";
					List<Entity> isInventory1=Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
					ErpInventory erpInventory1=new ErpInventory();
					//本次出库数量
					BigDecimal receiptQua=new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFQuantity());
					//修改数量=原有的数据-本次出库的数量*转换率
					//如果有的话就修改对应商品的库存
					if (isInventory1.size()>0)
					{
						BigDecimal aftBasicQua=isInventory1.get(0).getBigDecimal("f_basicamount");
						BigDecimal aftComamQua=isInventory1.get(0).getBigDecimal("f_comamount");
						erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
						erpInventory1.setFGoodsid(erpSalesoutbandenrtyListDto.get(i).getFGoodsid());
						erpInventory1.setFWarehouseid(erpSalesoutbandDto.getFWarehouseid());
						erpInventory1.setFBasicamount(aftBasicQua.subtract(receiptQua));
						erpInventory1.setFComamount(aftComamQua.subtract(receiptQua));
						//是否需要转换 需要的话就重新赋值
						if (!erpSalesoutbandenrtyListDto.get(i).getFComunit().equals(erpSalesoutbandenrtyListDto.get(i).getFUnit()))
						{
							erpInventory1.setFComamount(aftComamQua.subtract(receiptQua.multiply(comConverRate)));
						}
						else
						{
							erpInventory1.setFBasicamount(aftBasicQua.subtract(receiptQua.multiply(baseConverRate)));
						}
						erpInventoryService.updateById(erpInventory1);
						erpSalesorderentry.setFId(erpSalesoutbandenrtyListDto.get(i).getFOrderentryid());
						erpSalesorderentry.setFGoodsid(erpSalesoutbandenrtyListDto.get(i).getFGoodsid());
						//未出库数量=总数量-（已入库数量+本次入库数量）
						erpSalesorderentry.setFNooutqua(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFOrderqua()).subtract(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFOutqua()).add(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFQuantity()))).intValue());
						//已出库数量=总数量-未出库数量
						erpSalesorderentry.setFOutqua(new BigDecimal(erpSalesoutbandenrtyListDto.get(i).getFOrderqua()).subtract(new BigDecimal(erpSalesorderentry.getFNooutqua())).intValue());
						erpSalesorderentryList.add(erpSalesorderentry);
						if(erpSalesorderentry.getFNooutqua()<0||erpSalesorderentry.getFNooutqua()==0)
						{
							statusList.add(status);
						}
					}
				}
			}
		}
		//2.对销售订单的商品数量做修改（已出库数量、未出库数量）
		erpSalesorder.setFId(erpSalesoutbandDto.getFSalesorderid());
		//只有所有的已出库数量都等于0，才修改为已入库，否则还是部分出库
		if (statusList.size()==erpSalesoutbandenrtyListDto.size())
		{
			erpSalesorder.setFStatus(2);
		}
		else
		{
			erpSalesorder.setFStatus(0);
		}
		erpSalesorderService.updateById(erpSalesorder);
		erpSalesorderentryService.updateBatchById(erpSalesorderentryList);
		erpSalesoutbandenrtyList.forEach(erpSalesoutbandenrty -> {
			erpSalesorderentryList.forEach(erpSalesorderentry -> {
				if (erpSalesoutbandenrty.getFGoodsid() == erpSalesorderentry.getFGoodsid())
				{
					erpSalesoutbandenrty.setFOutqua(erpSalesorderentry.getFOutqua());
					erpSalesoutbandenrty.setFNooutqua(erpSalesorderentry.getFNooutqua());
				}
			});
		});
		return  null;
	}

    @SneakyThrows
	@Override
	public boolean updateErpSalesoutband(String id, ErpSalesoutband erpSalesoutband,ErpSalesoutbandDto erpSalesoutbandDto,List<ErpSalesoutbandenrtyDto> erpSalesoutbandenrtyListDto,List<ErpSalesoutbandenrty> erpSalesoutbandenrtyList) {
        if(updateInfo(erpSalesoutbandDto,erpSalesoutbandenrtyListDto,erpSalesoutbandenrtyList)==null){
            erpSalesoutband.setFId(id);
            erpSalesoutbandenrtyList.forEach(erpSalesoutbandenrty -> {erpSalesoutbandenrty.setFSalesoutid(id);});
            erpSalesoutbandenrtyMapper.delete(Wrappers.<ErpSalesoutbandenrty>query().lambda().eq(ErpSalesoutbandenrty::getFSalesoutid, id));

            this.saveBatch(erpSalesoutbandenrtyList, ErpSalesoutbandenrty.class, ErpSalesoutbandenrtyMapper.class);
            return this.updateById(erpSalesoutband);
        }
        else {
            return  false;
        }

	}

	public List<ErpSalesoutbandenrty> getErpSalesoutbandenrtyByParentId(String parentId){
		Wrapper wrapper = Wrappers.<ErpSalesoutbandenrty>query().lambda().eq(ErpSalesoutbandenrty::getFSalesoutid, parentId);
		return erpSalesoutbandenrtyMapper.selectList(wrapper);
	}
	public List<ErpSalesoutbandenrtyVo> getEntryInfo(String F_SalesOrderId)
	{
		return erpSalesoutbandenrtyMapper.getEntryInfo(F_SalesOrderId);
	}
}
